package com.example.helloword.controller;

import com.example.helloword.aop.metrics.MetricTime;
import com.example.helloword.dto.Message;
import com.example.helloword.servie.ServiceHandle;
import com.example.helloword.validator.custom.LoginVO;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


@Slf4j
@RestController
@Data
public class HelloController {
    private final ServiceHandle serviceHandle;

    @RequestMapping("/")
    @MetricTime("index")
    public String index() {
        serviceHandle.handle4();
        log.info("hello is log test");
        return "Hello every one";
    }

    @GetMapping("/testAsy")
    public String testAsy() throws InterruptedException, ExecutionException {

        Future<String> str1 = serviceHandle.handle1();
        Future<String> str2 = serviceHandle.handle2();
        Future<String> str3 = serviceHandle.handle3();

//        while (true) {
//            if (str1.isDone() && str2.isDone() && str3.isDone()) {
//                break;
//            }
//            Thread.sleep(500);
//        }

        getRet(str1, "1");
        getRet(str2, "2");
        getRet(str3, "3");
        log.info("all done");

        return "ok";
    }

    private void getRet(Future<String> str1, String desc) {
        try {
            String ret1 = str1.get();
            log.info("desc={} ok ret={}", desc, ret1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @PostMapping("/valid")
    public String customValid(@Valid @RequestBody LoginVO request) {
        log.info("{}", request);
        return "ok";
    }

    @RequestMapping("/jsonTest")
    public Message jsonTest() {
        Message message = new Message("1001", "message", new Date(), "extra");
        return message;
    }
}
